package cn.zhoutao.basic.service.impl;

import cn.zhoutao.auth.domain.Menu;
import cn.zhoutao.auth.mapper.MenuMapper;
import cn.zhoutao.auth.mapper.PermissionMapper;
import cn.zhoutao.basic.constants.BaseConstant;
import cn.zhoutao.basic.dto.LoginDto;
import cn.zhoutao.basic.dto.RegisterDto;
import cn.zhoutao.basic.dto.WeChatDto;
import cn.zhoutao.basic.exception.BusinessException;
import cn.zhoutao.basic.jwt.JwtUtils;
import cn.zhoutao.basic.jwt.LoginResult;
import cn.zhoutao.basic.jwt.RsaUtils;
import cn.zhoutao.basic.service.ILoginService;
import cn.zhoutao.basic.util.AjaxResult;
import cn.zhoutao.basic.util.HttpClientUtils;
import cn.zhoutao.basic.util.MD5Utils;
import cn.zhoutao.basic.util.StrUtils;
import cn.zhoutao.user.domain.Logininfo;
import cn.zhoutao.user.domain.User;
import cn.zhoutao.user.domain.Wxuser;
import cn.zhoutao.user.mapper.LogininfoMapper;
import cn.zhoutao.user.mapper.UserMapper;
import cn.zhoutao.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author:MrZhou
 * @Date:2022/6/18 19:32
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 账号密码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();

        //空校验
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||StringUtils.isEmpty(type)){
            throw new BusinessException("信息不能为空！");
        }
        //根据username＋type查询logininfo
       Logininfo logininfo =  logininfoMapper.loadByUsernameAndType(username,type);
        //查不到，密码错误
        if (logininfo==null){
            throw new BusinessException("用户名或者密码错误！");
        }
        //查到了，校验密码是否一致
        String salt = logininfo.getSalt();
        String md5pwd = MD5Utils.encrypByMd5(password + salt);

        if (!md5pwd.equalsIgnoreCase(logininfo.getPassword())){
            //密码不正确，报错
            throw new BusinessException("密码错误，请重新输入！");
        }
        //登陆成功
        return loginSuccessHandler(logininfo);
        // 存储redis
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象要序列化
                30,
                TimeUnit.MINUTES
        );
        //返回token+logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //考虑到一些敏感信息，不能返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
    }

    /**
     * 处理登陆相关的逻辑
     * @param logininfo
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //先判断是否是员工，如果是员工才需要查询权限 1=员工   0=用户
        if (logininfo.getType()==0){
            //徐查询出当前登录人对应的菜单和按钮权限
            //查询菜单权限
            List<Menu> menus = menuMapper.loadMenusByLoginInfoId(logininfo.getId());
            //查询按钮权限
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
            System.out.println(permissions);
        }

        //把登录人信息和权限封装成jwt串，返回给前端
        // 1 获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        //使用私钥把loginresult加密成jwt字符串
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);



        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);//此时的token是jwt字符串
        //考虑到一些敏感信息，不能返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        map.put("menus" ,loginResult.getMenus());
        map.put("permission",loginResult.getPermissions());
        return map;
    }

    /**
     * 微信三方登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
        String code = dto.getCode();
        //空校验
        if (code.isEmpty()){
            throw new BusinessException("网络繁忙！");
        }
        //通过code从微信获取token和openid
        String tokenUrl= BaseConstant.WeChatConstants.TOKEN_URL.replace("APPID",BaseConstant.WeChatConstants.APPID)
                                .replace("SECRET",BaseConstant.WeChatConstants.SECRET)
                                .replace("CODE",code);
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        JSONObject tokenObject = JSONObject.parseObject(tokenStr);//把字符串转化为一个对象
        String accessToken = tokenObject.getString("access_token");
        String openId = tokenObject.getString("openid");
        //通过openID查询t_wxuser表，判断wxuser是否存在，并且user_id不能为空
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        //wxuser存在，并且有user_id说明之前扫码登陆过，那么直接免密登录
        if (wxuser!=null &&wxuser.getUserId()!=null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            //存储redis
            /*String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,//对象要序列化
                    30,
                    TimeUnit.MINUTES
            );
            //返回token+logininfo
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //考虑到一些敏感信息，不能返回给前端
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);*/
            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));
        }
        //wxuser不存在跳转到绑定页面，输入账号密码完成绑定，返回token+openid
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;

        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    @Override
    public Map<String, Object> binder(WeChatDto dto) {
        User user = userMapper.loadByPhone(dto.getPhone());
        //根据username查询t_user是否存在
        //存在就查询出来绑定
        Logininfo logininfo = null;
        if (user!=null){
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }else{
            //不存在就生成新的t_user和t_logininfo
            user = dto2user(dto);//把dto转化成user对象
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //根据token和openID查询微信用户的基本信息
        String wxUserUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        //根据微信用户的基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        //根据t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
        //保存t_wxuser完成绑定
        wxuserMapper.save(wxuser);
        //免密登录
        //存储redis
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象要序列化
                30,
                TimeUnit.MINUTES
        );
        //返回token+logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //考虑到一些敏感信息，不能返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
        return loginSuccessHandler(logininfo);
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);//同名拷贝原则
        logininfo.setType(1);//必须手动设置type
        return logininfo;
    }

    private User dto2user(WeChatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
